package ml.stayfool.util;

import ml.stayfool.address.AddressInfo;
import ml.stayfool.configuration.ConfigProps;
import org.apache.hc.client5.http.impl.sync.HttpClients;
import org.apache.hc.client5.http.methods.HttpGet;
import org.apache.hc.client5.http.sync.HttpClient;
import org.apache.hc.client5.http.sync.ResponseHandler;
import org.apache.hc.core5.http.HttpResponse;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.entity.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Optional;

/**
 * Created by pactera on 2017/1/11.
 */
public class GPSUtil {

    private static HttpClient client = HttpClients.createDefault();
    private static JsonRespHandler jsonRespHandler = new JsonRespHandler();

    private static Logger logger = LoggerFactory.getLogger(GPSUtil.class);

    public static Optional<AddressInfo> getAddress(String gpsLocation) {
        Optional<AddressInfo> result = Optional.empty();
        try {
            HttpGet get = new HttpGet(ConfigProps.getApiUrl(gpsLocation));
            AddressInfo addressInfo = client.execute(get, jsonRespHandler);
            result = Optional.of(addressInfo);
        } catch (IOException e) {
            logger.error("query location by gps failed", e);
        }

        return result;
    }

    private static class JsonRespHandler implements ResponseHandler<AddressInfo> {
        @Override
        public AddressInfo handleResponse(HttpResponse httpResponse) throws IOException {
            int status = httpResponse.getStatusLine().getStatusCode();
            if (status == HttpStatus.SC_OK) {
                try {
                    String json = EntityUtils.toString(httpResponse.getEntity());
                    return JsonUtil.fromJson(json, AddressInfo.class);
                } catch (ParseException e) {
                    logger.error("query location by gps failed", e);
                }
            }
            return null;
        }
    }

    private GPSUtil() {
    }
}
